TOOL.Category		= "Wire - Detection"
TOOL.Name			= "Lagmeter"
TOOL.Command		= nil
TOOL.ConfigName		= ""
TOOL.Tab			= "Wire"

if ( CLIENT ) then
    language.Add( "Tool_wire_lagmeter_name", "lagmeter Tool (Wire)" )
    language.Add( "Tool_wire_lagmeter_desc", "Spawns a lagmeter for use with the wire system." )
    language.Add( "Tool_wire_lagmeter_0", "Primary: Create/Reset lagmeter" )
	language.Add( "undone_wirelagmeter", "Undone Wire lagmeter" )
end


TOOL.ClientConVar[ "model" ] = "models/beer/wiremod/gate_e2.mdl"

cleanup.Register( "wire_lagmeters" )

function TOOL:LeftClick( trace )
	if trace.Entity && trace.Entity:IsPlayer() then return false end
	if (CLIENT) then return true end

	local ply = self:GetOwner()

	// If we shot a wire_lagmeter do nothing
	if ( trace.Entity:IsValid() && trace.Entity:GetClass() == "gmod_wire_lagmeter" && trace.Entity.pl == ply ) then
		trace.Entity:Setup()
		return true
	end

	if ( !self:GetSWEP():CheckLimit( "wire_lagmeters" ) ) then return false end

	local Ang = trace.HitNormal:Angle()
	Ang.pitch = Ang.pitch + 90

	wire_lagmeter = MakeWirelagmeter( ply, trace.HitPos, Ang)

	local min = wire_lagmeter:OBBMins()
	wire_lagmeter:SetPos( trace.HitPos - trace.HitNormal * min.z )

	local const = WireLib.Weld(wire_lagmeter, trace.Entity, trace.PhysicsBone, true)

	undo.Create("Wirelagmeter")
		undo.AddEntity( wire_lagmeter )
		undo.AddEntity( const )
		undo.SetPlayer( ply )
	undo.Finish()

	ply:AddCleanup( "wire_lagmeters", wire_lagmeter )

	return true
end

if (SERVER) then

	function MakeWirelagmeter( pl, Pos, Ang )

		local wire_lagmeter = ents.Create( "gmod_wire_lagmeter" )
		if (!wire_lagmeter:IsValid()) then return false end

		wire_lagmeter:SetAngles( Ang )
		wire_lagmeter:SetPos( Pos )
		if(!model) then
			wire_lagmeter:SetModel( Model("models/jaanus/wiretool/wiretool_speed.mdl") )
		else
			wire_lagmeter:SetModel( Model(model) )
		end
		wire_lagmeter:Spawn()

		wire_lagmeter:Setup()
		wire_lagmeter:SetPlayer(pl)
		wire_lagmeter.pl = pl

		return wire_lagmeter
	end

end

function TOOL.BuildCPanel(panel)
	panel:AddControl("Header", { Text = "#Tool_wire_lagmeter_name", Description = "#Tool_wire_lagmeter_desc" })
end
